package language.advanced.reflect;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class getResourceTest {
    //springboot中getResource的几种用法：
    //方法二：File file3 = new File(Test.class.getResource("/javaapplication/file3.txt").getFile());

    @Test
    public void listFill() throws IOException, URISyntaxException {

        //从项目的ClassPath根下获取资源
        System.out.println(this.getClass().getResource("/")); //  target/classes/
        File file = new File(this.getClass().getResource("/test.js").toString());

        //path不以'/'开头时，默认是从本代码文件所在的包utils下取资源；
        System.out.println(this.getClass().getResource(""));  //  target/classes/utils/

        //获取本地maven仓库路径
        System.out.println(Test.class.getResource(""));
        //jar:file:/C:/Users/songyf/.m2/repository/junit/junit/4.12/junit-4.12.jar!/org/junit/

        System.out.println(this.getClass().getResourceAsStream("/"));

        //读取文件内容
        // Paths.get 参数是URI，getResource得到的结果是URL。 URI > URL
        Path path = Paths.get(this.getClass().getResource("/test.js").toURI());
        Files.readAllLines(path)
                .forEach(System.out::println);

        String s = IOUtils.toString(this.getClass().getResourceAsStream("/test.js"), StandardCharsets.UTF_8);
        System.out.println(s);

    }
}
